/**
 * Created by Administrator on 2017/5/11.
 */
import store from '../store'

let isNumber = function (value) {
  let patten = /^(-)?\d+(\.\d+)?$/;
  return !(patten.exec(value) === null || value === "");
}

let checkDecimal = function (value) {
  let arr = value.toString().split(".");
  return arr[1].length;
}

let isEmpty = function (e) {
  if (!e) {
    return false;
  }

  if (e instanceof Array && e.length !== 0) {
    return true;
  }

  let t;
  for (t in e)
    return !1;
  return !0
}


let formatChinaTime = function (time, format) {
  var t = new Date(time);
  var tf = function (i) {
    return (i < 10 ? '0' : '') + i
  };
  return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a) {
    switch (a) {
      case 'yyyy':
        return tf(t.getFullYear());
        break;
      case 'MM':
        return tf(t.getMonth() + 1);
        break;
      case 'mm':
        return tf(t.getMinutes());
        break;
      case 'dd':
        return tf(t.getDate());
        break;
      case 'HH':
        return tf(t.getHours());
        break;
      case 'ss':
        return tf(t.getSeconds());
        break;
    }
  });
}

let copyProperties = function (o) {
  return JSON.parse(JSON.stringify(o));
}

let hasPermission = function (perms = [], operate = 'and') {
  let currentStaff = store.state.staff.loginStaff;


  if (currentStaff.admin) {
    return true;
  }
  let matchAmount = 0;
  for (let i = 0; i < currentStaff.permissions.length; i++) {
    let allPer = currentStaff.permissions[i];
    for (let j = 0; j < perms.length; j++) {
      let _per = perms[j];
      if (_per === allPer) {
        matchAmount++;
        if (operate === 'or' || (operate === 'and' && matchAmount === perms.length)) {
          return true;
        }
      }
    }
  }
  return false;
};

let arrayModelToString = function (array, property, delim = ',') {
  let result = '';
  let length = array.length;
  for (let i = 0; i < length; i++) {
    result += array[i][property];
    if (i < length - 1) {
      result += delim;
    }
  }
  return result;
}

let arrayToString = function (array, delim = ',') {
  let result = '';
  let length = array.length;
  for (let i = 0; i < length; i++) {
    result += array[i];
    if (i < length - 1) {
      result += delim;
    }
  }
  return result;
}

let utils = {
  isNumber: isNumber,
  isEmpty: isEmpty,
  arrayModelToString: arrayModelToString,
  arrayToString: arrayToString,
  checkDecimal: checkDecimal,
  hasPermission: hasPermission,
  formatChinaTime: formatChinaTime,
  copyProperties: copyProperties
}
const install = function (Vue, opts = {}) {
  Vue.prototype.$utils = utils;
};


export default install
